﻿using System;
using System.Text;

namespace Apewer.Models
{

    /// <summary>日志条目。</summary>
    [Serializable]
    public sealed class LogItem
    {

        /// <summary>自定义日志条目格式化程序。</summary>
        public static Func<LogItem, string> Formatter { get; set; }

        /// <summary>日志记录程序。</summary>
        public Logger Logger { get; internal set; }

        /// <summary>记录日志的时间。</summary>
        public DateTime Clock { get; private set; }

        /// <summary>日志的标签。</summary>
        public string Tag { get; internal set; }

        /// <summary>日志的文本内容。</summary>
        public object[] Content { get; internal set; }

        /// <summary>日志中包含的异常对象。</summary>
        public Exception Exception { get; internal set; }

        /// <summary></summary>
        internal LogItem()
        {
            Clock = DateTime.Now;
        }

        /// <summary></summary>
        public override string ToString()
        {
            var formatter = Formatter;
            if (formatter != null) return formatter.Invoke(this);

            var sb = new StringBuilder();
            var written = 0;

            sb.Append(ClockUtility.Lucid(Clock));
            written++;

            if (!string.IsNullOrEmpty(Tag))
            {
                sb.Append("  [");
                sb.Append(Tag);
                sb.Append("]");
                written++;
            }

            if (Exception != null)
            {
                sb.Append("  <");
                sb.Append(Exception.GetType().Name);
                sb.Append("> ");
                sb.Append(Exception.Message());
                written++;
            }

            if (Content != null && Content.Length > 0)
            {
                var content = TextUtility.Join(" | ", Content);
                if (!string.IsNullOrEmpty(content))
                {
                    if(written > 1) sb.Append(" | ");
                    else sb.Append("  ");
                    sb.Append(content);
                }
            }

            return sb.ToString();
        }

    }

}
